/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  if (l1.val == 0 && !l1.next) {
    return l2
  }
  if (l2.val == 0 && !l2.next) {
    return l1
  }

  let result = l1
  let resultNext = result

  let pre = 0
  do {
    let num = pre
    num += l1 ? l1.val : 0
    num += l2 ? l2.val : 0
    resultNext.val = num % 10
    pre = num >= 10 ? 1 : 0
    l1 = l1 ? l1.next : null
    l2 = l2 ? l2.next : null

    resultNext.next = resultNext.next || l2

    if (resultNext.next) {
      resultNext = resultNext.next
    }
  } while (l1 || l2)

  if (pre) {
    resultNext.next = new ListNode(pre)
  }

  return result
}
// @lc code=end

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val
  this.next = next === undefined ? null : next
}
// let l1 = new ListNode()
// l1.val = 2
// l1.next = new ListNode(4, new ListNode(3))

// let l2 = new ListNode()
// l2.val = 5
// l2.next = new ListNode(6, new ListNode(4))
let l1 = new ListNode()
l1.val = 2
l1.next = new ListNode(4, new ListNode(9))

let l2 = new ListNode()
l2.val = 5
l2.next = new ListNode(6, new ListNode(4, new ListNode(9)))

console.log(JSON.stringify(addTwoNumbers(l1, l2)))
